#include "editlock.h"
#include "ui_editlock.h"
#include "mainwindow.h"

//将输入，每16个字符加密一次
void my_encrypt(AESModeOfOperation *moo, unsigned char *input, int len, QString path)
{
    int round = len%16>0 ? len/16+1 : len/16;
    int n = 0;
    unsigned char *output = (unsigned char *)malloc(16);
    memset(output, 0, 16);
    QFile file(path+"password.txt");
    if (!file.open(QIODevice::WriteOnly))return;
    QDataStream out(&file);
    do {
        n = len>16 ? moo->Encrypt(input, 16, output) : moo->Encrypt(input, len, output);
        for (int i = 0; i < n; i++)
        {
            out << output[i];
        }
        memset(output, 0, 16);
        input = input+n;
        round--;
        len = len-n;
    }while (round > 0);
    file.close();
    free(output);
}

editlock::editlock(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::editlock)
{
    ui->setupUi(this);
}

editlock::editlock(QString password, QString path, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::editlock)
{
    ui->setupUi(this);
    this->password = password;
    this->path = path;
}

editlock::~editlock()
{
    delete ui;
}

void editlock::on_backButton_clicked()
{
    this->close();
    emit back_newlock_signal();
}

void editlock::on_confirmButton_clicked()
{
    //采用AES算法加密
    QString str = ui->locksEdit->toPlainText();
    unsigned char iv[] = {103,35,148,239,76,213,47,118,255,222,123,176,106,134,98,92};
    unsigned char *input = QString2Input(str);
    unsigned char *key = QString2Key(password);
    AESModeOfOperation moo;
    moo.set_key(key);
    moo.set_mode(MODE_OFB);
    moo.set_iv(iv);
    int length = 0;
    QByteArray ba = str.toLocal8Bit();
    char *ptr = ba.data();
    while (*ptr != 0)
    {
        ptr++;
        length++;
    }
    my_encrypt(&moo, input, length, path);
    free(input);
    free(key);
}
